package com.project.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@ComponentScan("com.project.service")
@ComponentScan("com.project.mapper")
@MapperScan("com.project.mapper")
@EnableTransactionManagement
public class MyBatisConfig {
    @Bean
    public DataSource getSource(){
        DruidDataSource source = new DruidDataSource();
        source.setDriverClassName("com.mysql.jdbc.Driver");
        source.setUrl("jdbc:mysql://localhost:12345/dormitory?characterEncoding=utf-8&allowMultiQueries=true");
        source.setUsername("root");
        source.setPassword("lovo");
        source.setMaxActive(100);
        source.setMinIdle(20);
        source.setMaxWait(1000);
        return source;
    }
    @Bean
    public FactoryBean getFactoryBean(){
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(this.getSource());
        factory.setConfigLocation(new ClassPathResource("mybatis.cfg.xml"));

        return factory;
    }
    @Bean
    public TransactionManager getManage(){
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        manager.setDataSource(this.getSource());
        return manager;
    }
}
